import json, os
from datetime import datetime
import Reloading
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
def AutoSave (player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders):
    filename = os.path.join (os.getcwd (), 'Archive', 'autosave.json')
    time = datetime.now ()
    save_time = (f"{time.year}年{time.month}月{time.day}日 {time.hour}:{time.minute}:{time.second :1d}")
    data = {
        'save_time': save_time,
        'warehouse_level': warehouse_level,
        'player_level': player_level,
        'player_xp': player_xp,
        'customer_name': customer_name,
        'customer_need': customer_need, 
        'map': map, 
        'money': money, 
        'year': year, 
        'day': day, 
        'week': week, 
        'month': month, 
        'seventh_shops_discount': seventh_shops_discount, 
        'discount_num': discount_num, 
        'player_warehouse_list': player_warehouse_list, 
        'player_warehouse_list_name': player_warehouse_list_name, 
        'original_price': original_price, 
        'all_sold_count': all_sold_count, 
        'all_day_count': all_day_count, 
        'time_hour': time_hour, 
        'time_minute': time_minute, 
        'time_second': time_second, 
        'acc_num': acc_num, 
        'times_serve': times_serve, 
        'times_orders': times_orders, 
        'sold_time': sold_time, 
        'story_num': story_num, 
        'price_up_amplitude': price_up_amplitude, 
        'orders': orders,
        'player_shop_name': player_shop_name
    }
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4)  # indent 美化输出
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
def SaveArchive (player_shop_name, save, mode, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders):
    while (1):
        try :
            time = datetime.now ()
            save_time = (f"{time.year}年{time.month}月{time.day}日 {time.hour}:{time.minute}:{time.second :1d}")
            print ("\033[39;33m|---------------------------------------")
            print ("\033[39;33m|\033[38;5;37m自动存档：")
            print ("\033[39;33m|\033[38;5;165m=======================================")
            current_dir = os.path.join (os.getcwd (), 'Archive', 'AutoSave')
            has_files = any (os.path.isfile (os.path.join (current_dir, item)) for item in os.listdir (current_dir))
            if (not has_files):
                print ("\033[39;33m|\033[0m暂无自动存档")
            else :
                current_dir = os.path.join (os.getcwd (), 'Archive', 'AutoSave', 'autosave.json')
                with open (current_dir, 'r', encoding = 'utf-8') as f:
                    data = json.load (f)
                print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{data["save_time"]}")
                print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{data["money"]}₿")
                print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{data["player_level"]}级")
                print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{data["warehouse_level"]}级")
            print ("\033[39;33m|---------------------------------------")
            current_dir = os.path.join (os.getcwd (), 'Archive')
            print ("|\033[38;5;37m存档目录：")
            num = 1
            all_items = os.listdir (current_dir)
            num_dir = os.path.join (os.getcwd (), 'SystemFile', 'saveNum.json')
            with open(num_dir, 'r', encoding = 'UTF-8') as nd:
                save_num = json.load (nd)['save_num']
                if (len (save_num) == 0):
                    mode = 1
            for i in range (10):
                if (num <= 10):
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                if ((str (i + 1) + '.json') in all_items):
                    if (mode == 1):
                        print (f"\033[39;33m|\033[38;5;33m{num}.")
                        current_dir = os.path.join (os.getcwd (), 'Archive', str (i + 1) + '.json')
                        with open(current_dir, 'r', encoding = 'utf-8') as d:
                            read_data = json.load (d)
                        print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                        print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                        print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                        print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                        print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                    elif (mode == 2):
                        print (f"\033[39;33m|\033[39;32m{num}.")
                        current_dir = os.path.join (os.getcwd (), 'Archive', str (i + 1) + '.json')
                        with open(current_dir, 'r', encoding = 'utf-8') as d:
                            read_data = json.load (d)
                        print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                        print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                        print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                        print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                        print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                    else :
                        print (f"\033[39;33m|\033[39;31m{num}.")
                        current_dir = os.path.join (os.getcwd (), 'Archive', str (i + 1) + '.json')
                        with open(current_dir, 'r', encoding = 'utf-8') as d:
                            read_data = json.load (d)
                        print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                        print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                        print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                        print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                        print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                else :
                    if (mode == 1):
                        print (f"\033[39;33m|\033[39;32m{num}. \033[0m无存档")
                    else :
                        print (f"\033[39;33m|\033[0m{num}. 无存档")
                num += 1
            print ("\033[39;33m|---------------------------------------")
            mode_list = ["\033[31m删除存档\033[0m", "\033[32m保存存档\033[0m", "\033[m载入存档\033[0m"]
            print (f"\033[33m|\033[0m当前模式为\"{mode_list [mode]}\"")
            if (mode == 1):
                print ("\033[39;33m|\033[39;32mx. 输入对应序号以覆盖或初次存档")
            elif (mode == 0):
                print ("\033[39;33m|\033[39;31mx. 输入对应序号以删除存档")
            elif (mode == 2):
                print ("\033[39;33m|\033[mx. 输入对应序号以载入存档")
            if (has_files and mode == 1):
                print ("\033[39;33m|\033[32mAu. 读取自动存档")
            if (mode != 0):
                print ("\033[39;33m|\033[31mDe. \033[0m切换为“\033[39;31m删除存档\033[0m”模式")
            if (mode != 1):
                print ("\033[39;33m|\033[32mSa. \033[0m切换为“\033[39;32m保存存档\033[0m”模式")
            if (mode != 2):
                print ("\033[39;33m|\033[36mLa. \033[0m切换为“\033[39;36m载入存档\033[0m”模式")
            print ("\033[39;33m|\033[31m0. 返回")
            print ("\033[39;33m|---------------------------------------\033[0m")
            chos = input ("输入需要的功能：")
            os.system ('cls')
            if (chos in ['De', 'Sa', 'La']):
                if (chos == 'De'):
                    if (mode != 0 and len (save_num) > 0):
                        mode = 0
                    elif (mode != 0 and len (save_num) == 0):
                        os.system ('cls')
                        print ("暂无存档！")
                    elif (mode == 0):
                        raise ValueError
                elif (chos == 'La'):
                    if (mode != 2 and len (save_num) > 0):
                        mode = 2
                    elif (mode != 2 and len (save_num) == 0):
                        os.system ('cls')
                        print ("暂无存档！")
                    elif (mode == 1):
                        raise ValueError
                elif (chos == 'Sa'):
                    if (mode != 1):
                        mode = 1
                    else :
                        raise ValueError
            elif (chos == 'Au'):
                pass
            elif (int (chos) == 0):
                return player_shop_name, save, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders
            elif (mode in [0, 1]):
                if (int (chos) not in save_num and mode == 0):
                    os.system ('cls')
                    print ("\033[1;31m该位置无存档！\033[0m\n")
                elif (mode == 0):
                    os.system ('cls')
                    current_dir = os.path.join (os.getcwd (), 'Archive', chos + '.json')
                    print (f"\033[31m你确定要删除{int (chos)}号存档吗？")
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                    with open(current_dir, 'r', encoding = 'utf-8') as d:
                        read_data = json.load (d)
                    print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                    print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                    print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                    print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                    print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                    print ("\033[31m请注意，被删除的存档将无法恢复！")
                    print ("输入Yes确认退出(区分大小写)！\n输入其他任意内容返回。\033[0m")
                    mode = input ()
                    if (mode == 'Yes'):
                        save= 1
                        os.remove (os.path.join (os.getcwd(), 'Archive' , chos + '.json'))
                        del save_num[save_num.index (int (chos))]
                        with open (num_dir, 'r', encoding = 'UTF-8') as nd:
                            data = json.load (nd)
                        del data["save_num"][data["save_num"].index (int (chos))]
                        with open (num_dir, 'w', encoding="utf-8") as nd:
                            json.dump (data, nd, indent = 4)
                        Reloading.DeleteArchive ()
                    mode = 0
                elif (mode == 1):
                    if (int (chos) in save_num):
                        current_dir = os.path.join (os.getcwd (), 'Archive', chos + '.json')
                        print (f"你确定要保存并覆盖{int (chos)}号存档吗？")
                        print ("\033[39;33m|\033[38;5;165m=======================================")
                        with open(current_dir, 'r', encoding = 'utf-8') as d:
                            read_data = json.load (d)
                        print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                        print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                        print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                        print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                        print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                        print ("\033[39;33m|\033[38;5;165m=======================================")
                        print ("\033[31m请注意，被覆盖的存档将无法恢复！")
                        print ("输入Yes确认覆盖存档(区分大小写)！\n输入其他任意内容返回。\033[0m")
                        choos = input ()
                        if (choos == 'Yes'):
                            save= 1
                            os.system ('cls')
                            Write (player_shop_name, chos, save_time, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders)
                            with open (num_dir, 'r', encoding = 'UTF-8') as nd:
                                data = json.load (nd)
                            with open (num_dir, 'w', encoding="utf-8") as nd:
                                json.dump (data, nd, indent = 4)
                            Reloading.CoverArchive ()
                            os.system ('cls')
                        else :
                            os.system ('cls')
                            print ("\033[1;31m取消覆盖存档\033[0m\n")
                    else :
                        Write (player_shop_name, chos, save_time, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders)
                        save = 1
                        with open (num_dir, 'r', encoding = 'UTF-8') as nd:
                            data = json.load (nd)
                            data["save_num"].append (int (chos))
                        with open (num_dir, 'w', encoding="utf-8") as nd:
                            json.dump (data, nd, indent = 4)
                        Reloading.SaveArchive ()
                        os.system ('cls')
            elif (mode == 2):
                if (int (chos) not in save_num and mode == 0):
                    os.system ('cls')
                    print ("\033[1;31m该位置无存档！\033[0m\n")
                else :
                    current_dir = os.path.join (os.getcwd (), 'Archive', chos + '.json')
                    print (f"你确定要载入{int (chos)}号存档吗？")
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                    with open(current_dir, 'r', encoding = 'utf-8') as d:
                        read_data = json.load (d)
                    print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                    print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                    print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                    print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                    print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                    print ("\033[31m请注意，被载入覆盖的存档将无法恢复！")
                    print ("输入Yes确认载入(区分大小写)！\n输入其他任意内容返回。\033[0m")
                    choos = input ()
                    if (choos == 'Yes'):
                        player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders = Read (chos)
                        os.system ('cls')
                    else :
                        os.system ('cls')
                        print ("\033[1;31m取消载入存档\033[0m\n")
            else :
                raise ValueError
        except ValueError:
            os.system ('cls')
            print ("\033[1;31m无效选项！\033[0m\n")
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
def Write (player_shop_name, file_num, save_time, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders):
    while (1):
        remark = input ("书写备注(15字以内，可不写)：")
        if (len (remark) > 15):
            print ("备注请在15字以内。")
        elif (0 < len (remark) <= 15):
            break
        elif (len (remark) == 0):
            remark = "无备注"
            break
    filename = os.path.join (os.getcwd (), 'Archive', file_num + '.json')
    data = {
            'remark': remark,
            'save_time': save_time,
            'warehouse_level': warehouse_level,
            'player_level': player_level,
            'player_xp': player_xp,
            'customer_name': customer_name,
            'customer_need': customer_need, 
            'map': map, 
            'money': money, 
            'year': year, 
            'day': day, 
            'week': week, 
            'month': month, 
            'seventh_shops_discount': seventh_shops_discount, 
            'discount_num': discount_num, 
            'player_warehouse_list': player_warehouse_list, 
            'player_warehouse_list_name': player_warehouse_list_name, 
            'original_price': original_price, 
            'all_sold_count': all_sold_count, 
            'all_day_count': all_day_count, 
            'time_hour': time_hour, 
            'time_minute': time_minute, 
            'time_second': time_second, 
            'acc_num': acc_num, 
            'times_serve': times_serve, 
            'times_orders': times_orders, 
            'sold_time': sold_time, 
            'story_num': story_num, 
            'price_up_amplitude': price_up_amplitude, 
            'orders': orders,
            'player_shop_name': player_shop_name
        }
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4)  # indent 美化输出
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
def Read (chos):
    filename = os.path.join (os.getcwd (), 'Archive', chos + '.json')
    with open(filename, 'r', encoding='utf-8') as f:
        load_data = json.load(f)
    warehouse_level = load_data['warehouse_level']
    player_level = load_data['player_level']
    player_xp = load_data['player_xp']
    customer_name = load_data['customer_name']
    customer_need = load_data['customer_need']
    map = load_data['map']
    money = load_data['money']
    year = load_data['year']
    day = load_data['day']
    week = load_data['week']
    month = load_data['month']
    seventh_shops_discount = load_data['seventh_shops_discount']
    discount_num = load_data['discount_num']
    player_warehouse_list = load_data['player_warehouse_list']
    player_warehouse_list_name = load_data['player_warehouse_list_name']
    original_price = load_data['original_price']
    all_sold_count = load_data['all_sold_count']
    all_day_count = load_data['all_day_count']
    time_hour = load_data['time_hour']
    time_minute = load_data['time_minute']
    time_second = load_data['time_second']
    acc_num = load_data['acc_num']
    times_serve = load_data['times_serve']
    times_orders = load_data['times_orders']
    sold_time = load_data['sold_time']
    story_num = load_data['story_num']
    price_up_amplitude = load_data['price_up_amplitude']
    orders = load_data['orders']
    player_shop_name = load_data['player_shop_name']
    return player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
def OpenRead ():
    while (1):
        try:
            print ("\033[39;33m|---------------------------------------")
            print ("\033[39;33m|\033[38;5;37m自动存档：")
            print ("\033[39;33m|\033[38;5;165m=======================================")
            current_dir = os.path.join (os.getcwd (), 'Archive', 'AutoSave')
            has_files = any (os.path.isfile (os.path.join (current_dir, item)) for item in os.listdir (current_dir))
            if (not has_files):
                print ("\033[39;33m|\033[0m暂无自动存档")
            else :
                current_dir = os.path.join (os.getcwd (), 'Archive', 'AutoSave', 'autosave.json')
                with open (current_dir, 'r', encoding = 'utf-8') as f:
                    data = json.load (f)
                print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{data["save_time"]}")
                print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{data["money"]}₿")
                print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{data["player_level"]}级")
                print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{data["warehouse_level"]}级")
            print ("\033[39;33m|---------------------------------------")
            current_dir = os.path.join (os.getcwd (), 'Archive')
            print ("|\033[38;5;37m存档目录：")
            num = 1
            all_items = os.listdir (current_dir)
            num_dir = os.path.join (os.getcwd (), 'SystemFile', 'saveNum.json')
            with open(num_dir, 'r', encoding = 'UTF-8') as nd:
                save_num = json.load (nd)['save_num']
                if (len (save_num) == 0):
                    mode = 1
            for i in range (10):
                if (num <= 10):
                    print ("\033[39;33m|\033[38;5;165m=======================================")
                if ((str (i + 1) + '.json') in all_items):
                    print (f"\033[39;33m|\033[39;32m{num}.")
                    current_dir = os.path.join (os.getcwd (), 'Archive', str (i + 1) + '.json')
                    with open(current_dir, 'r', encoding = 'utf-8') as d:
                        read_data = json.load (d)
                    print (f"\033[39;33m|\033[1;39;36m存档备注:\033[0m{read_data["remark"]}")
                    print (f"\033[39;33m|\033[1;39;36m存档时间:\033[0m{read_data["save_time"]}")
                    print (f"\033[39;33m|\033[1;39;36m持有金钱:\033[0m{read_data["money"]}₿")
                    print (f"\033[39;33m|\033[1;39;36m玩家等级:\033[0m{read_data["player_level"]}级")
                    print (f"\033[39;33m|\033[1;39;36m仓库等级:\033[0m{read_data["warehouse_level"]}级")
                else :
                    print (f"\033[39;33m|\033[0m{num}. 无存档")
                num += 1
            print ("\033[39;33m|---------------------------------------")
            print ("\033[39;33m|\033[mx. 输入对应序号以载入存档")
            print ("\033[39;33m|\033[31m0. 返回")
            print ("\033[39;33m|---------------------------------------\033[0m")
            chos = int (input ("输入需要的功能："))
            if (chos in save_num):
                read = 1
                player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders = Read (str (chos))
                return read, player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders
            elif (chos == 0):
                read = 0
                return read, player_shop_name, warehouse_level, player_level, player_xp, customer_name, customer_need, map, money, year, day, week, month, seventh_shops_discount, discount_num, player_warehouse_list, player_warehouse_list_name, original_price, all_sold_count, all_day_count, time_hour, time_minute, time_second, acc_num, times_serve, times_orders, sold_time, story_num, price_up_amplitude, orders
        except ValueError:
            os.system ('cls')
            print ("\033[1;31m无效选项！\033[0m\n")
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
if __name__ == "__main__": # 仅当这个文件本身被执行的时候才会运行
    OpenRead ()